package org.swift.mashup.engine.deployment.mcr;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.swift.mashup.engine.deployment.MessageContextReader;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestHeadersMessageContextReader implements MessageContextReader {
	private static RequestHeadersMessageContextReader instance = null;

	public static RequestHeadersMessageContextReader getInstance() {
		if (instance == null) {
			instance = new RequestHeadersMessageContextReader();
		}
		return instance;
	}

	private RequestHeadersMessageContextReader() {
	}


	@Override
	public Map<String, Object> createParameterMap(MessageContext context) {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		HttpServletRequest request = (HttpServletRequest)context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);

		if ( request != null ) {
			Enumeration headerNames = request.getHeaderNames();
			while ( headerNames != null && headerNames.hasMoreElements() ) {
				String name = (String) headerNames.nextElement();
				StringBuilder sb = new StringBuilder();

				Enumeration values = request.getHeaders(name);
				int count = 0;
				while ( values != null && values.hasMoreElements() ) {
					if ( count > 0 ) {
						sb.append(',');
					}
					sb.append(values.nextElement());
					count += 1;
				}

				String value = sb.toString().trim();

				if ( !value.isEmpty() ) {
					paramMap.put(name, value);
				}
			}
		}

		return paramMap;
	}
}
